<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';

import { ChevronsLeft, ChevronsRight } from '@vben/icons';

import { ElCard } from 'element-plus';

interface Props {
  // 初始是否折叠
  defaultCollapsed?: boolean;
  // 展开时的宽度
  expandedWidth?: string;
  // 折叠时的宽度
  collapsedWidth?: string;
  // 是否响应式（自动根据屏幕宽度折叠）
  responsive?: boolean;
  // 响应式断点
  breakpoint?: number;
}

const props = withDefaults(defineProps<Props>(), {
  defaultCollapsed: false,
  expandedWidth: '16rem', // w-64
  collapsedWidth: '3rem', // w-12
  responsive: true,
  breakpoint: 1024,
});

const collapsed = ref(props.defaultCollapsed);

// 动态监听窗口尺寸变化
const updateScreenSize = () => {
  if (!props.responsive || collapsed.value === true) {
    return;
  }
  collapsed.value = window.innerWidth <= props.breakpoint;
};

// 切换展开/收起
function toggleCollapse() {
  collapsed.value = !collapsed.value;
}

onMounted(() => {
  updateScreenSize();
  window.addEventListener('resize', updateScreenSize);
});

onUnmounted(() => {
  window.removeEventListener('resize', updateScreenSize);
});

// 暴露方法给父组件
defineExpose({
  collapsed,
  toggleCollapse,
});
</script>

<template>
  <ElCard
    class="sticky h-full overflow-hidden transition-all duration-300"
    :class="{
      'w-64': !collapsed,
      'w-12': collapsed,
    }"
  >
    <!-- 表单区域，隐藏时使用 v-show + transition -->
    <transition name="fade">
      <div v-show="!collapsed" class="transition-all duration-300">
        <slot></slot>
      </div>
    </transition>
    <!-- 展开/收起按钮区域 -->
    <div
      class="flex-center hover:text-foreground text-foreground/60 hover:bg-accent-hover bg-accent absolute right-3 top-2 z-10 cursor-pointer rounded-sm p-1"
    >
      <ChevronsRight v-if="collapsed" class="size-4" @click="toggleCollapse" />
      <ChevronsLeft v-else class="size-4" @click="toggleCollapse" />
    </div>
  </ElCard>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
